<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button v-if="hasPermission([PermissionEnum.MODEL_MANAGE])" type="primary" @click="handleCreate"> 新增数据模型 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="createActions(record)"
          />
        </template>
      </template>
    </BasicTable>
    <EntityDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { useDrawer } from '@/components/Drawer';
  import EntityDrawer from './EntityDrawer.vue';
  import { columns, searchFormSchema } from './data';
  import { getEntityList, deleteEntity } from '@/api/entity'
  import { useMessage } from '@/hooks/web/useMessage';

  import { usePermission } from '@/hooks/web/usePermission';
  import { PermissionEnum } from '@/enums/permissionEnum'
  
  const { hasPermission } = usePermission();

  const { notification } = useMessage();

  const createActions = (record) => {
    const actions: ActionItem[] = [
      {
        label: '编辑',
        ifShow: hasPermission([PermissionEnum.MODEL_MANAGE]),
        onClick: () => {
          handleEdit(record);
        },
      },
      {
        label: '删除',
        ifShow: hasPermission([PermissionEnum.MODEL_MANAGE]),
        color: 'error',
        popConfirm: {
          title: '确认删除？',
          confirm: () => {
            handleDelete(record);
          },
        },
      },
    ];
    return actions;
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload }] = useTable({
    api: getEntityList,
    columns,
    formConfig: {
      labelWidth: 50,
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    bordered: true,
    showIndexColumn: true,
    actionColumn: {
      width: 80,
      title: '操作',
      dataIndex: 'action',
      fixed: undefined,
    },
  });

  function handleCreate() {
    openDrawer(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  }

  function handleDelete(record: Recordable) {
    deleteEntity(record.id).then(() => {
      notification.success({
        message: '',
        description: '删除成功',
        duration: 2,
      });
      reload();
    }).catch(error => {
      notification.error({
        message: '',
        description: '删除失败',
        duration: 2,
      });
    });
  }

  function handleSuccess() {
    reload();
  }
</script>